package cn.jsu.oj.dispatchServer.init;

import cn.jsu.oj.dispatchServer.dataStructure.MessageQueue;
import cn.jsu.oj.dispatchServer.factory.CmdHandleFactory;
import cn.jsu.oj.dispatchServer.handle.CommandPack;
import cn.jsu.oj.dispatchServer.handle.handles.ThreadCloseHandle;
import cn.jsu.oj.dispatchServer.pojo.AbstractPack;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadPoolExecutor;


/**
 * @author ahtonc
 */
@Slf4j
public abstract class AbstractClientInit implements ClientInit {

    protected Channel channel;


    protected MessageQueue<Object> messageQueue;
    protected boolean isClose = false;

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    public MessageQueue<Object> getMessageQueue() {
        return messageQueue;
    }

    public void setMessageQueue(MessageQueue<Object> messageQueue) {
        this.messageQueue = messageQueue;
    }

    @Override
    public void addTask(Object object) {
        messageQueue.add(object);
    }

    @Override
    public void init(Channel context) {
        this.channel = context;
    }

    @Override
    public void close() {
        //将信息转移到错误大队列
//        while (!messageQueue.isEmpty()) {
//            Object o = messageQueue.poll();
//            if (o != null) {
//                Resource.errorQueue.add(new CommandPack<AbstractPack>(channel, (AbstractPack) o));
//            }
//        }
        messageQueue.clear();
        //改变线程状态,添加信息唤醒线程
        isClose = true;
        messageQueue.add(new ThreadCloseHandle());
        //关闭通道
        if (channel != null) {
            channel.close();
        }
    }

    @Override
    public void run() {
        while (!isClose)
        {
            try {
                //获取信息
                AbstractPack pack = (AbstractPack) messageQueue.take();
                //创建commandPack
                CommandPack<?> commandPack = new CommandPack<>(channel, pack);
                //获取处理类并执行
                CmdHandleFactory.getHandle(pack.getTypeNo()).handle(commandPack);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
